package com.andrew.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.andrew.entity.Cart;
import com.andrew.entity.Customer;
import com.andrew.service.CartService;
import com.andrew.service.CustomerService;
import com.andrew.service.impl.CartServiceImpl;
import com.andrew.service.impl.CustomerServiceImpl;

/**
 * Servlet implementation class CheckUserServlet
 */
public class CheckUserServlet extends HttpServlet {

	private CustomerService customerService =new CustomerServiceImpl();
	private CartService cartService=new CartServiceImpl();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		//获取参数
		String phone=req.getParameter("phone");
		String password=req.getParameter("password");
		
		//创建封装对象
		Customer customer=null;
		//查询用户，并封装
		try {
			customer =customerService.login(phone, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//用户名密码错误
		if(customer==null) {
			//没有这个人
			System.out.println("查无此人");
			resp.getWriter().write("false");
			return;
		}
		
		//查询当前用户的cart对象，并封装
		Cart cart=null;
		try {
			cart = cartService.getCart(customer.getCustomerId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//用户名密码正确
		resp.getWriter().write("true");
		//保存当前用户的信息与购物车信息
		req.getSession().setAttribute("customer",customer );
		req.getSession().setAttribute("cart",cart );
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
